package com.nextbusmn.server.services;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.nextbusmn.server.JDOWrappers.ScheduleDateJDOWrapper;
import com.nextbusmn.server.JSONBuilders.UpdateJSONBuilder;

public class UpdateService implements AndroidService {

	private HttpServletResponse response;
	
	public UpdateService(HttpServletResponse response) {
		this.response = response;
	}
	
	@Override
	public void processRequest() {
		try {
			JSONObject jsonResponse = getScheduleUpdateDate();
			
			response.setContentType("application/json");
	        response.setHeader("Cache-Control", "no-cache");
	        response.getWriter().write(jsonResponse.toString());
	        
		} catch (IOException e) {
			AndroidService errorService = 
					new ErrorService("IOError on Update Service response", response);
			errorService.processRequest();
		}

	}
	
	private JSONObject getScheduleUpdateDate() {
		Date date = ScheduleDateJDOWrapper.getCurrentScheduleDate();
		return UpdateJSONBuilder.getUpdateJSON(date);
	}

}
